<template>
  <view class="familySharing flex flex-column align-center bg_F5F5F5">
    <view class="flex flex-column align-center wh_750"
          style="position: fixed;top: 0;left:50%;transform: translateX(-50%)">
      <s-header-title ref="headerTitle" title="家庭二维码" isDisplayBack is-fixed background="transparent"
                      @getPageHeight="getPageHeight"></s-header-title>
      <view :style="{height:`${page.headerHeight}px`}"></view>
      <scroll-view scroll-y
                   class="wh_750"
                   :style="{
                      height:`calc(100vh - ${page.headerHeight}px)`
                   }"
      >
        <view class="wh_750 flex flex-column align-center">
          <view class="hW_30"></view>
          <canvas id="myCanvas" canvas-id="myCanvas"
                  style="position: fixed;top: -9999999999px;bottom:-999999999999px;z-index: 999999;"
                  :style="{width:`${page.canvasInfo.width}px`,height:`${page.canvasInfo.height}px`}"></canvas>
          <image :src="QRCode.shareFamilyImage"
                 :style="{width:`${page.canvasInfo.width}px`,height:`${page.canvasInfo.height}px`}"></image>
          <view class="hW_30"></view>
          <view class="bottom flex align-center justify-between">
            <view class="item flex align-center justify-center" @click.stop="savePicture">保存图片</view>
            <!-- #ifdef H5 -->
            <button class="item flex align-center justify-center" style="margin: 0!important;" @click.stop="wxShare">
              立即分享
            </button>
            <!-- #endif -->
            <!-- #ifdef MP-WEIXIN -->
            <button open-type="share" class="item flex align-center justify-center" style="margin: 0!important;">
              立即分享
            </button>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS -->
            <button class="item flex align-center justify-center" style="margin: 0!important;" @click.stop="wxShare">
              微信分享
            </button>
            <!-- #endif -->
          </view>
          <!-- app分享微信小程序canvas -->
          <!-- #ifdef APP-PLUS -->
          <canvas canvas-id="canvasShare" id="canvasShare" :style="{
      width:`${page.canvasWidth}px`,
      height:`${page.canvasHeight}px`
    }" style="position: fixed;top: -9999999999px;bottom:-999999999999px;z-index: 999999;"></canvas>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <view v-if="page.showShareGuide"
                class="guide-wrap"
                @click.stop="page.showShareGuide = false"
          >
            <image
              class="guide-image"
              :src="sheep.$url.static('/assets/addons/shopro/uniapp/share/share_guide.png')"
            ></image>
          </view>
          <!-- #endif -->
        </view>
        <view class="hW_150"></view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
  import HeaderTitle from '@/pages/familyPage/components/headerTitle.vue';
  import { computed, onMounted, reactive } from 'vue';
  import { onLoad, onReady, onShareAppMessage } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import { h5_url } from '@/sheep/config';

  const page = reactive({
    options: {},
    pageOptions: {},
    headerHeight: 0,
    canvasInfo: {
      width: 226,
      height: 402,
    },
    canvasWidth: 0,
    canvasHeight: 0,
    showShareGuide: false,
  });
  const QRCode = reactive({
    info: {},
    myCanvas: null,
    shareFamilyImage: '',
  });
  const systemInfo = computed(() => sheep.$platform.device);
  // #ifdef H5
  const userInfo = computed(() => JSON.parse(uni.getStorageSync('user-store')).userInfo);
  // #endif
  // #ifndef H5
  const userInfo = computed(() => sheep.$store('user').userInfo);
  // #endif
  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const nc_image = computed(() => sheep.$store('AI').nc_image);

  onLoad(async (options) => {
    if (!!options.spid) {
      sheep.$store('AI').setBindId(options.spid);
    }
    page.pageOptions = options;
    page.options = JSON.parse(uni.getStorageSync('setFamilyShare'));
  });
  onReady(async () => {
    await getFamilyQRCode();
    await drawShare();
    // #ifdef H5
    sheep.$platform.share.updateShareInfo({
      title: '拾亲',
      desc: `${userInfo.value.nickname}欢迎您加入${page.options.name}`,
      link: `${h5_url}/#/pages/message/genealogy?fd=${page.options.family_id}&t=1&f=1&id=${userInfo.value.uid}&spid=${userInfo.value.uid}`,
      image: `${h5_url}/static/fenxiang_icon.png`,
    });
    // #endif
  });

  function getPageHeight(number) {
    page.headerHeight = number;
  }

  // 获取家庭二维码
  async function getFamilyQRCode() {
    console.log(userInfo.value);
    const { data } = await sheep.$api.family.createFamilyCode({
      family_id: page.pageOptions.family_id,
      page: 'pages/message/genealogy',
      type: 1,
      is_flag: 1,
      uid: userInfo.value.uid,
      spid: userInfo.value.uid,
    });
    QRCode.info = data;
  }

  // 绘制分享海报
  async function drawShare() {
    uni.showLoading({
      title: '正在生成中',
      mask: true,
    });
    page.canvasInfo.width = (systemInfo.value.screenWidth / 750) * 452 * 1.5;
    page.canvasInfo.height = (systemInfo.value.screenWidth / 750) * 804 * 1.5;
    let ratio = 750 / systemInfo.value.screenWidth;
    let backgroundImage = '';
    let downloadFile = await uni.downloadFile({
      url: `${IMG_URL.value}/index/jiating_haipaoBg.png`,
    });
    console.log('downloadFile=>', downloadFile);
    let promise = await new Promise((resolve, reject) => {
      // #ifdef MP
      uni.getFileSystemManager().saveFile({
        tempFilePath: downloadFile.tempFilePath,
        success: (info) => {
          resolve(info.savedFilePath);
        },
      });
      // #endif
      // #ifndef MP
      resolve(downloadFile.tempFilePath);
      // #endif
    });
    backgroundImage = promise;

    // 绘制背景
    let ctx = uni.createCanvasContext('myCanvas', QRCode.myCanvas);
    await ctx.drawImage(backgroundImage, 0, 0, 452 / ratio * 1.5, 804 / ratio * 1.5);
    let avatar = '';
    let downloadAvatarFile = await uni.downloadFile({
      url: userInfo.value.avatar.indexOf('http') != -1 ? userInfo.value.avatar : `${nc_image.value}${userInfo.value.avatar}`,
    });
    let promiseAvatar = await new Promise((resolve, reject) => {
      // #ifdef MP
      uni.getFileSystemManager().saveFile({
        tempFilePath: downloadAvatarFile.tempFilePath,
        success: (info) => {
          resolve(info.savedFilePath);
        },
      });
      // #endif
      // #ifndef MP
      resolve(downloadAvatarFile.tempFilePath);
      // #endif
    });
    console.log('promiseAvatar=>', promiseAvatar);
    avatar = promiseAvatar;
    await ctxCircular(ctx, avatar, 14 / ratio * 1.5, 20 / ratio * 1.5, 60 / ratio * 1.5, 60 / ratio * 1.5, 60 / 2 / ratio * 1.5, 0);
    await ctx.save();
    await ctxTextWrapB(ctx, `邀请人: ${userInfo.value.nickname}`, 82 / ratio * 1.5, 35 / ratio * 1.5, 452 / ratio * 1.5, Math.floor(16 / ratio * 1.5), '#FFFFFF', '500', 'left');
    await ctxTextWrapB(ctx, `拾亲号: ${userInfo.value.uid}`, 82 / ratio * 1.5, 52 / ratio * 1.5, 452 / ratio * 1.5, Math.floor(16 / ratio * 1.5), '#FFFFFF', '500', 'left');


    await ctxTextWrapB(ctx, page.options.name, 226 / ratio * 1.5, 135 / ratio * 1.5, 452 / ratio * 1.5, Math.floor(28 / ratio * 1.5), '#FAE6BC', '500');
    await ctxTextWrapB(ctx, `家庭号: ${page.options.code}`, 226 / ratio * 1.5, 159 / ratio * 1.5, 452 / ratio * 1.5, Math.floor(16 / ratio * 1.5), '#FFFFFF', '500');
    // 绘制二维码
    let code = '';
    let downloadCodeFile = await uni.downloadFile({
      url: QRCode.info.qrcode_url,
    });
    let promiseCode = await new Promise((resolve, reject) => {
      // #ifdef MP
      uni.getFileSystemManager().saveFile({
        tempFilePath: downloadCodeFile.tempFilePath,
        success: (info) => {
          resolve(info.savedFilePath);
        },
      });
      // #endif
      // #ifndef MP
      resolve(downloadCodeFile.tempFilePath);
      // #endif
    });
    console.log(promiseCode);
    code = promiseCode;
    console.log('code=>', code);
    await ctx.save();
    await ctxCircular(ctx, code, 159 / ratio * 1.5, 177 / ratio * 1.5, 134 / ratio * 1.5, 134 / ratio * 1.5, 134 / 2 / ratio * 1.5, 0, true);
    await ctx.save();
    await ctxTextWrapB(ctx, '扫一扫进入家庭', 226 / ratio * 1.5, 316 / ratio * 1.5, 452 / ratio * 1.5, Math.floor(14 / ratio * 1.5), '#FFFFFF', '500');
    await ctx.save();
    await ctxTextWrapB(ctx, page.options.name, 226 / ratio * 1.5, 432 / ratio * 1.5, 452 / ratio * 1.5, Math.floor(14 / ratio * 1.5), '#FDCF4D', '500');
    await ctx.draw(false, () => {
      uni.canvasToTempFilePath({
        canvasId: 'myCanvas',
        fileType: 'png',
        quality: 1,
        // #ifdef APP-PLUS
        destWidth: 452 * 5,
        destHeight: 804 * 5,
        // #endif
        // #ifdef APP-PLUS
        destWidth: 452 * 10,
        destHeight: 804 * 10,
        // #endif
        success: (res) => {
          uni.hideLoading();
          QRCode.shareFamilyImage = res.tempFilePath;
        },
      });
    });
  }

  async function ctxCircular(ctx, img, x, y, width, height, r, shadow, flag = false) {
    ctx.fillStyle = '#fff';
    ctx.beginPath(); //开始绘制
    ctx.save(); //保存(canvas)状态
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + width - r, y);
    ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
    ctx.lineTo(x + width, y + height - r);
    ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * 0.5);
    ctx.lineTo(x + r, y + height);
    ctx.arc(x + r, y + height - r, r, Math.PI * 0.5, Math.PI);
    ctx.lineTo(x, y + r);
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
    if (shadow == 1) {
      ctx.shadowBlur = 0; // 模糊效果程度的
      ctx.shadowColor = 'red'; // 阴影颜色
    }
    ctx.fill(); //对当前路径中的内容进行填充
    ctx.clip(); //从原始画布中剪切任意形状和尺寸
    ctx.closePath(); //关闭一个路径
    if (flag) {
      ctx.drawImage(img, x + width * 0.1 / 2, y + height * 0.1 / 2, width * 0.9, height * 0.9);
    } else {
      ctx.drawImage(img, x, y, width, height);
    }
    ctx.restore(); //恢复(canvas)状态
    ctx.globalCompositeOperation = 'source-over';
  }

  async function ctxTextWrapB(ctx, text, x, y, w, size, color, weight, type = 'center') {
    //自动换行介绍
    let temp = '';
    let row = [];
    let gxqm = '';
    if (text) {
      gxqm = text;
    } else {
      gxqm = '未设置家谱名称';
    }
    let gexingqianming = gxqm.split('');
    for (let a = 0; a < gexingqianming.length; a++) {
      if (ctx.measureText(temp).width < w) {
      } else {
        row.push(temp);
        temp = '';
      }
      temp += gexingqianming[a];
    }
    row.push(temp);
    ctx.font = `arail normal ${weight} ${size}px sans-serif`;
    ctx.textAlign = type;
    ctx.fillStyle = `${color}`;
    ctx.globalCompositeOperation = 'source-over';
    if (row.length > 2) {
      let arr = row.splice(0, 3);
      for (let b = 0; b < arr.length; b++) {
        if (b + 1 == arr.length) {
          let str = arr[b].slice(0, -3) + '...';
          ctx.fillText(str || '...', x, y + (b + 1) * 15);
        } else {
          ctx.fillText(arr[b] || '', x, y + (b + 1) * 15);
        }
      }
    } else {
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b] || '', x, y + (b + 1) * 10);
      }
    }
  }

  // 保存图片
  function savePicture() {
    // #ifdef H5
    if (['WechatOfficialAccount', 'H5'].includes(sheep.$platform.name)) {
      sheep.$helper.toast('请长按图片保存');
      return;
    }
    // #endif
    // #ifdef MP
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.writePhotosAlbum']) {
          // 判断授权成功开始下载
          phonoDown();
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success: (res) => {
              // 判断授权成功开始下载
              phonoDown();
            },
          });
        } else {
          // 跳转授权页面
          // #ifdef MP
          uni.openSetting({
            success: (res) => {
              if (res.authSetting['scope.writePhotosAlbum']) {
                phonoDown();
              }
            },
          });
          // #endif
        }
      },
      fail: function(error) {
        // 失败错误信息输出
        console.log(error, 'getSetting');
      },
    });
    // #endif
    // #ifdef APP-PLUS
    phonoDown();
    // #endif
  }

  function phonoDown() {
    uni.saveImageToPhotosAlbum({
      filePath: QRCode.shareFamilyImage,
      success: () => {
        sheep.$helper.toast('已保存到相册');
      },
      fail: (error) => {
        console.log('保存失败', error);
      },
    });
  }

  // #ifdef MP-WEIXIN
  onShareAppMessage(() => {
    console.log(userInfo, page);
    return {
      title: `${userInfo.value.nickname}欢迎您加入${page.options.name}`,
      // #ifdef MP
      path: `/pages/message/genealogy?fd=${page.options.family_id}&t=1&f=1&id=${userInfo.value.uid}&spid=${userInfo.value.uid}`,
      // #endif
      // #ifndef MP
      path: `/pages/message/genealogy?fd=${page.options.family_id}&t=1&f=1&id=${userInfo.value.uid}&spid=${this.userInfo.uid}`,
      // #endif
      imageUrl: QRCode.shareFamilyImage,
    };
  });
  // #endif

  function wxShare() {
    // #ifdef H5
    page.showShareGuide = true;
    // #endif

    // #ifdef APP-PLUS
    sheep.$platform.share.shareAPP({
      title: `${userInfo.value.nickname}欢迎您加入${page.options.name}`,
      desc: '再小的家庭-也要有传承',
      link: `pages/message/genealogy?fd=${page.options.family_id}&t=1&f=1&id=${userInfo.value.uid}&spid=${userInfo.value.uid}`,
      image: `${h5_url}/static/shiqin_transparent_icon.png`,
    });
    // #endif
  }
</script>


<style scoped lang="scss">
  .familySharing {
    /* #ifdef H5 */
    margin: auto;
    /* #endif */
    width: 750rpx;
    min-height: 100vh;
    background: url($uni-bg-url-sq + '/index/jiating_fenxiang_bg.png') no-repeat;
    background-size: 100% 100%;
    overflow: hidden;

    .familySharing_code {
      width: 475rpx;
      height: 475rpx;
      background: #FFFFFF;
      border-radius: 20rpx;
      overflow: hidden;

      image {
        width: 447rpx;
        height: 447rpx;
      }
    }
  }

  .info {
    width: 562rpx;

    .familySharing_code_info {
      .familySharing_code_info_name {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 36rpx;
        color: #000000;
      }

      .familySharing_code_info_code {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 28rpx;
        color: #4B4B4B;
      }
    }
  }

  .tips {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 26rpx;
    color: #4B4B4B;
  }

  .bottom {
    width: 529rpx;

    .item {
      width: 201rpx;
      height: 70rpx;
      background: #FF4206;
      border-radius: 35rpx 35rpx 35rpx 35rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 28rpx;
      color: #FFFFFF;
    }
  }

  /* #ifdef H5 */
  .guide-wrap {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10070;
    background: rgba(0, 0, 0, 0.6);
  }

  .guide-image {
    right: 30rpx;
    top: 0;
    position: fixed;
    width: 580rpx;
    height: 430rpx;
    z-index: 10080;
  }

  /* #endif */
</style>
